package com.lc.controller;

import com.lc.bean.User;
import com.lc.bean.UserPossword;
import com.lc.config.BusinessException;
import com.lc.config.CommonErrorCode;
import com.lc.service.UserPasswordService;
import com.lc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserPasswordService userPasswordService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login/{name}/{pwd}")
    public HashMap<String,Object> login (@PathVariable String name, @PathVariable String pwd) throws Exception {
        HashMap<String,Object> map=new HashMap();
        try {
            User user =userService.selectByname(name);
            UserPossword password=userPasswordService.selectByuId(user.getId());
            if(password.getPwd().equals(pwd)){
                redisTemplate.opsForValue().set("user",user);
                map.put("mas","欢迎登录");
            }
        }catch (Exception e){
            throw new BusinessException(CommonErrorCode.E_1000);
        }
        return map;
    }

    @PostMapping("/updatepassword/{name}/{pwd}")
    @Transactional
    public HashMap<String,Object> updatepassword (@PathVariable String name, @PathVariable String pwd) throws Exception {
       HashMap<String,Object> map=new HashMap<>();
        User user =userService.selectByname(name);
        UserPossword password=userPasswordService.selectByuId(user.getId());
       boolean a= userPasswordService.updatepwd(user.getId());
       password.setPwd(pwd);
       String id = UUID.randomUUID().toString();
       password.setId(id);

//     SimpleDateFormat date=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());
       password.setTime(new Date());
       boolean b= userPasswordService.addpwd(password);
       if (a==true&&b==true){
           map.put("msg","修改成功");
       }
        return map;
    }
}
